package com.henry;

import com.alibaba.fastjson.JSON;
import com.aliyun.alidns20150109.Client;
import com.aliyun.alidns20150109.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;


public class Main {
    //配置文件路径
    private static final String filename = "./config.json";
    // 配置文件
    private static JsonConfig cfg = null;
    // 客户端
    private static Client client = null;
    // 域名IP
    private static String recordsValue = "";
    // 记录类型
    private static final String recordType = "A";
    // 上次域名查询时间
    private static long lastDnsTime = 0;
    // 上次公网ip查询时间
    private static long lastIpTime = 0;


    public static void main(String[] args) throws Exception {
        Main.readJsonFile();
        Main.Initialization();
        Main.run();
    }

    /**
     * 读取配置文件
     */
    private static void readJsonFile() {
        // 读取配置文件信息
        String Context = JsonUtils.readJsonFile(filename);
        cfg = JSON.parseObject(Context, JsonConfig.class);
        if (cfg == null) {
            System.out.println("读取配置文件" + filename + "失败");
        }
    }

    /**
    * 初始化公共请求参数
    */
    public static void Initialization() throws Exception {
        Config config = new Config();
        // 您的AccessKey ID
        config.accessKeyId = cfg.accessKeyId;
        // 您的AccessKey Secret
        config.accessKeySecret = cfg.secret;
        // 您的可用区ID
        config.regionId = cfg.regionId;
        client = new Client(config);
    }

    private static void run() throws Exception {
        while (true) {
            long now = System.currentTimeMillis();

            //  当前主机公网IP
            String ip = IpUtils.getPublicIP();

            // 查询域名服务器值是否改变
            if (lastDnsTime < now) {
                check(ip);
                lastIpTime = now + cfg.ipInterval;
                lastDnsTime = now + cfg.dnsInterval;
            }

            // 公网IP是否发生改变
            if (lastIpTime < now) {
                if (ip != null && !ip.equals(recordsValue)) {
                    check(ip);
                    lastDnsTime = now + cfg.dnsInterval;
                }
                lastIpTime = now + cfg.ipInterval;
            }

            try {
                // 进程睡眠释放CPU并达到延迟效果
                Thread.sleep(Math.min(lastIpTime, lastDnsTime) - now - 1);
            } catch (InterruptedException ignored) {
            }
        }
    }

    private static void check(String ip) throws Exception {
        DescribeDomainRecordsResponse resp = Main.DescribeDomainRecords(client, cfg.tld,recordType);
        if (Common.isUnset(TeaModel.buildMap(resp)) || Common.isUnset(TeaModel.buildMap(resp.body.domainRecords.record.get(0)))) {
            com.aliyun.teaconsole.Client.log("错误参数！");
            return ;
        }

        String currentHostIP = IpUtils.getPublicIP();

        for (int i = 0; i < resp.body.domainRecords.record.size(); i++) {
            DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord record = resp.body.domainRecords.record.get(i);
            // 记录ID
            String recordId = record.recordId;
            // 记录值
            recordsValue = record.value;
            com.aliyun.teaconsole.Client.log("-------------------当前主机公网IP为：" + currentHostIP + "--------------------");
            if (!Common.equalString(currentHostIP, recordsValue)) {
                // 修改解析记录
                UpdateDomainRecordRequest req = new UpdateDomainRecordRequest();
                // 主机记录
                req.RR = record.getRR();
                // 记录ID
                req.recordId = recordId;
                // 将主机记录值改为当前主机IP
                req.value = currentHostIP;
                // 解析记录类型
                req.type = recordType;
                Main.UpdateDomainRecord(client, req);
            }
    }
}

    /**
     * 获取主域名的所有解析记录列表
     */
    public static DescribeDomainRecordsResponse DescribeDomainRecords(Client client, String tld, String recordType) throws Exception {
        DescribeDomainRecordsRequest req = new DescribeDomainRecordsRequest();
        // 主域名
        req.domainName = tld;
        // 主机记录
        //req.RRKeyWord = RR;
        // 解析记录类型
        req.type = recordType;
        try {
            DescribeDomainRecordsResponse resp = client.describeDomainRecords(req);
            com.aliyun.teaconsole.Client.log("-------------------获取主域名的所有解析记录列表--------------------");
            com.aliyun.teaconsole.Client.log(Common.toJSONString(TeaModel.buildMap(resp)));
            return resp;
        } catch (TeaException error) {
            com.aliyun.teaconsole.Client.log(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            com.aliyun.teaconsole.Client.log(error.message);
        }
        return null;
    }

    /**
     * 修改解析记录
     */
    public static void UpdateDomainRecord(Client client, UpdateDomainRecordRequest req) throws Exception {
        try {
            UpdateDomainRecordResponse resp = client.updateDomainRecord(req);
            com.aliyun.teaconsole.Client.log("-------------------修改解析记录--------------------");
            com.aliyun.teaconsole.Client.log(Common.toJSONString(TeaModel.buildMap(resp)));
        } catch (TeaException error) {
            com.aliyun.teaconsole.Client.log(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            com.aliyun.teaconsole.Client.log(error.message);
        }
    }
}

